package com.itheima.servlet;

import com.alibaba.fastjson.JSON;
import com.itheima.bean.Brand;
import com.itheima.service.BrandService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet("/selectByIdServlet")
public class SelectByIdServlet extends HttpServlet {

    private final BrandService brandService = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        System.out.println("我的id是" + id);
        //将id放到会话域中
        req.getSession().setAttribute("id",id);
        //跳转到修改页面
        resp.sendRedirect("alter-brand.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String id = (String) session.getAttribute("id");
        System.out.println("取出的id是 "+ id);
        //取出id后让会话失效
        session.invalidate();
        int hId = Integer.parseInt(id);
        Brand brand = brandService.selectById(hId);
        String s = JSON.toJSONString(brand);
        resp.getWriter().print(s);
    }
}
